<template>
  <div id="pictureDetailPage">
    <a-row :gutter="[16, 16]">
      <!-- 图片预览 -->
      <a-col :sm="24" :md="md">
        <a-card title="点击图片预览">
          <a-image
            :alt="picture.name"
            :src="picture.url"
            style="max-height: 560px; object-fit: contain"
          />
        </a-card>
      </a-col>
      <!-- 图片信息区域 -->
      <a-col :sm="24" :md="24 - md">
        <a-card title="图片信息">
          <a-descriptions :column="1">
            <a-descriptions-item label="分享者">
              <a-space>
                <a-avatar :size="24" :src="picture.user?.userAvatar" />
                <div>{{ picture.user?.userName }}</div>
              </a-space>
            </a-descriptions-item>
            <a-descriptions-item label="图片名">
              {{ picture.name ?? '未命名' }}
            </a-descriptions-item>
            <a-descriptions-item label="简介">
              {{ picture.introduction ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="分类">
              {{ picture.category ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="标签">
              <a-tag v-for="tag in picture.tags" :key="tag">
                {{ tag }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="格式">
              {{ picture.picFormat ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="宽度">
              {{ picture.picWidth ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="高度">
              {{ picture.picHeight ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="宽高比">
              {{ picture.picScale ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="大小">
              {{ formatSize(picture.picSize) }}
            </a-descriptions-item>
            <a-descriptions-item label="主色调">
              <a-space>
                {{ toHexColor(picture.picColor) ?? '-' }}
                <div
                  v-if="picture.picColor"
                  :style="{
                    backgroundColor: toHexColor(picture.picColor),
                    width: '16px',
                    height: '16px',
                  }"
                />
              </a-space>
            </a-descriptions-item>
            <a-descriptions-item label="创建时间">
              {{ dayjs(picture.createTime).format('YYYY-MM-DD HH:mm:ss') }}
            </a-descriptions-item>
          </a-descriptions>
          <!-- 图片操作 -->
          <a-space wrap>
            <a-button
              type="primary"
              title="下载原图"
              @click="downloadOrigin"
              v-if="picture.originView === 1"
            >
              下载
              <template #icon>
                <DownloadOutlined />
              </template>
            </a-button>
            <a-button
              type="primary"
              title="下载高清压缩图"
              @click="downloadCompressed"
              v-if="picture.originView === 0"
            >
              下载
              <template #icon>
                <DownloadOutlined />
              </template>
            </a-button>
            <a-button
              type="primary"
              title="下载缩略图"
              @click="downloadThumbnail"
              v-if="buttonShow"
            >
              缩略
              <template #icon>
                <CompressOutlined />
              </template>
            </a-button>
            <a-button
              type="primary"
              title="抓取相似图片"
              @click="toSearchPicturePage"
              v-if="buttonShow"
            >
              相似
              <template #icon>
                <SearchOutlined />
              </template>
            </a-button>
            <a-button
              type="primary"
              title="分享这张图片给小伙伴"
              @click="doShare"
              v-if="buttonShow"
            >
              分享
              <template #icon>
                <ShareAltOutlined />
              </template>
            </a-button>
            <a-button
              v-if="canEdit"
              title="编辑图片信息"
              :icon="h(EditOutlined)"
              type="primary"
              @click="doEdit"
            >
              编辑
            </a-button>
            <a-button
              v-if="canReview && pictureForReview.reviewStatus !== PIC_REVIEW_STATUS_ENUM.REJECT"
              :icon="h(CloseOutlined)"
              title="打回该图片，不通过审核"
              link
              danger
              @click="handleReview(picture, PIC_REVIEW_STATUS_ENUM.REJECT)"
            >
              打回
            </a-button>
            <a-button
              v-if="canReview && pictureForReview.reviewStatus !== PIC_REVIEW_STATUS_ENUM.PASS"
              :icon="h(CheckOutlined)"
              title="过审该图片"
              link
              @click="handleReview(picture, PIC_REVIEW_STATUS_ENUM.PASS)"
            >
              过审
            </a-button>
            <a-popconfirm
              title="确定删除该图片吗？"
              ok-text="确认"
              cancel-text="取消"
              @confirm="doDelete"
              @cancel="cancelDelete"
            >
              <a href="#">
                <a-button
                  v-if="canEdit"
                  title="删除图片"
                  :icon="h(DeleteOutlined)"
                  danger
                  type="primary"
                >
                  删除
                </a-button>
              </a>
            </a-popconfirm>
          </a-space>
        </a-card>
      </a-col>
    </a-row>
    <ShareModal ref="shareModalRef" :link="shareLink" />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, h, computed } from 'vue'
import {
  getPictureVoByIdUsingGet,
  deletePictureUsingPost,
  doPictureReviewUsingPost,
  getPictureByIdUsingGet,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { downloadImage, formatSize } from '@/utils/index.ts'
import {
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined,
  CheckOutlined,
  CloseOutlined,
  CompressOutlined,
  SearchOutlined,
  ShareAltOutlined,
} from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStores.ts'
import { useRouter } from 'vue-router'
import { PIC_REVIEW_STATUS_ENUM } from '@/constants/picture.ts'
import dayjs from 'dayjs'
import { toHexColor } from '@/utils/HexColor.ts'
import ShareModal from '@/components/ShareModal.vue'

interface Props {
  id: string | number
}

const loginUserStore = useLoginUserStore()
const loginUser = loginUserStore.loginUser
const router = useRouter()

const props = defineProps<Props>()

const picture = ref<API.PictureVO>({})

const pictureForReview = ref<API.Picture>({})

const md = ref<number>(18)

/**
 * 校验当前用户是否有权编辑或删除当前图片
 */
const canEdit = computed(() => {
  // 未登录不能编辑
  if (!loginUser.id) {
    return false
  }
  // 图片位于公共图库，仅图片创建人或者管理员可以编辑图片
  // 如果图片位于个人云，只有空间管理者可以编辑
  if (picture.value.spaceId === null) {
    return loginUser.id === picture.value?.userId || loginUser.userRole === 'admin'
  } else {
    return loginUser.id === picture.value?.userId
  }
})

/**
 * 校验当前用户是否有权审核当前图片
 */
const canReview = computed(() => {
  // @ts-ignore
  const loginUser = loginUserStore.loginUser
  // 未登录不能审核
  if (!loginUser.id) {
    return false
  }
  // 仅管理员可以审核图片
  // 位于个人云的图片不需要审核
  if (picture.value.spaceId === null) {
    return loginUser.userRole === 'admin'
  } else {
    return false
  }
})

const buttonShow = computed(() => {
  if (picture.value.spaceId === null) {
    return true
  } else {
    return loginUser.id === picture.value?.userId
  }
})

/**
 * 获取图片（非图片视图）
 * @param id
 */
// @ts-ignore
const getPictureById = async (id) => {
  const res = await getPictureByIdUsingGet({ id })
  if (res.data.code === 0 && res.data.data) {
    pictureForReview.value = res.data.data
  }
}

/**
 * 点击图片卡片跳转后，根据id获取图片详情数据
 */
const fetchPictureDetail = async () => {
  try {
    const res = await getPictureVoByIdUsingGet({
      // @ts-ignore
      id: props.id,
    })
    if (res.data.code === 0 && res.data.data) {
      picture.value = res.data.data
      getPictureById(picture.value.id)
      changeMd()
    } else {
      message.error('抱歉，' + res.data.message)
    }
  } catch (e: any) {
    message.error('获取图片详情失败，' + e.message)
  }
}

// 下载原图
const downloadOrigin = () => {
  downloadImage(picture.value.originUrl)
}

// 下载压缩图
const downloadCompressed = () => {
  downloadImage(picture.value.url)
}

// 下载缩略图
const downloadThumbnail = () => {
  downloadImage(picture.value.thumbnailUrl)
}

// 搜索相似图
const toSearchPicturePage = () => {
  // 携带参数跳转识图页面
  window.open(`/search_picture?pictureId=${picture.value.id}`)
}

// 分享弹窗引用
const shareModalRef = ref()
// 分享链接
const shareLink = ref<string>()
// 分享
const doShare = () => {
  shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.value.id}`
  if (shareModalRef.value) {
    shareModalRef.value.openModal()
  }
}

// 编辑图片
const doEdit = () => {
  if (loginUser.id !== picture.value.userId && loginUser.userRole !== 'admin') {
    message.error('无权编辑图片信息')
    return
  }
  router.push({
    path: '/edit_picture',
    query: {
      id: picture.value.id,
      spaceId: picture.value.spaceId,
    },
  })
}

// 删除图片
const doDelete = async () => {
  if (picture.value.spaceId !== null && loginUser.userRole !== 'admin') {
    if (loginUser.id !== picture.value.userId) {
      message.error('无权删除图片')
      return
    }
  }
  const id = props.id
  if (!id) {
    message.error('删除失败，该图片已不存在')
    return
  }
  // @ts-ignore
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除图片成功，三秒后返回上一页')
    // 因为点击图片卡后是跳到新页面打开图片详情
    // 所有删除图片后，直接关闭当前页面
    // 延迟 3000 毫秒（3 秒）后关闭页面
    setTimeout(() => {
      // 三秒后关闭当前页面
      window.close()
    }, 3500)
  } else {
    message.error('删除图片失败，' + res.data.message)
  }
}

/**
 * 审核图片
 * @param pictureVO
 * @param reviewStatus
 */
const handleReview = async (pictureVO: API.PictureVO, reviewStatus: number) => {
  if (picture.value.spaceId !== null) {
    message.error('无效审核操作')
    return
  }
  if (loginUser.userRole !== 'admin') {
    message.error('无权审核图片')
    return
  }
  const reviewMessage =
    reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '管理员操作通过' : '管理员操作拒绝'
  // @ts-ignore
  const res = await doPictureReviewUsingPost({
    id: pictureVO.id,
    reviewStatus,
    reviewMessage,
  })
  if (res.data.code === 0) {
    message.success('审核操作成功')
    // 审核操作后重新获取数据 变化操作按钮
    getPictureById(pictureVO.id)
  } else {
    message.error('审核操作失败，' + res.data.message)
  }
}

const cancelDelete = (e: MouseEvent) => {
  message.success('取消删除')
}

const changeMd = () => {
  const loginUser = loginUserStore.loginUser
  // 公共图库
  if (picture.value.spaceId === null) {
    if (loginUser.userRole === 'admin') {
      md.value = 17
    } else if (loginUser.id === picture.value?.userId) {
      md.value = 18
    } else {
      md.value = 17
    }
  } else {
    // 私有空间
    if (loginUser.id === picture.value?.userId) {
      md.value = 18
    } else {
      md.value = 24
    }
  }
}

// 首次进入图片详情页，加载数据，改变两侧长度
onMounted(() => {
  // changeMd()函数 执行在 fetchPictureDetail()函数内，保证 picture一定正确获得
  fetchPictureDetail()
})
</script>

<style scoped>
#pictureDetailPage {
  margin-bottom: 16px;
}
</style>
